package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.mapper.DtsPermissionMapper;
import com.qf.pojo.DtsPermission;
import com.qf.service.DtsPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 金园
 * @create 2022/5/17
 * @Description
 * @className DtsPermissionServiceImpl
 * @packageName com.qf.service.impl
 */
@Service
public class DtsPermissionServiceImpl implements DtsPermissionService {
    @Autowired
    DtsPermissionMapper permissionMapper;
    @Override
    public Set<String> findPermById(Integer[] roleIds) {
        LambdaQueryWrapper<DtsPermission> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.in(DtsPermission::getRoleId,roleIds);
        List<DtsPermission> permissions = permissionMapper.selectList(queryWrapper);
//        Set<String> ps = permissions.stream().map(permission -> {
//            return permission.getPermission();
//        }).collect(Collectors.toSet());
        return permissions.stream().map(permission -> {
            return permission.getPermission();
        }).collect(Collectors.toSet());
    }

    @Override
    public Set<String> findPermByIds(Integer[] roleIds) {
        LambdaQueryWrapper<DtsPermission> qw = new LambdaQueryWrapper<>();
        qw.in(DtsPermission::getRoleId, roleIds);
        List<DtsPermission> permissionList = permissionMapper.selectList(qw);
        Set<String> permissions = permissionList.stream().map(permission -> {
            return permission.getPermission();
        }).collect(Collectors.toSet());
        System.out.println(permissions);
        return permissions;
    }

    @Override
    public void updateByrole(Integer roleId, ArrayList<String> permissions) {
        //删除原来的权限
        LambdaQueryWrapper<DtsPermission> qw = new LambdaQueryWrapper();
        qw.eq(DtsPermission::getRoleId,roleId);
        permissionMapper.delete(qw);
        //添加新选择的权限
        if (permissions != null && permissions.size()>0){
            for (String permission : permissions) {
                DtsPermission dtspermission = new DtsPermission();
                dtspermission.setUpdateTime(new Date());
                dtspermission.setAddTime(new Date());
                dtspermission.setDeleted(false);
                dtspermission.setRoleId(roleId);
                dtspermission.setPermission(permission);
                permissionMapper.insert(dtspermission);
            }

        }

                                            
    }
}
